package com.edge.pbx.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;

import com.qztech.utils.YzDebug;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 深圳市东乘电子科技有限公司
 * Carate By YangZhong
 */
public class PbxImageButtonRadioLayout extends LinearLayout implements View.OnClickListener {
    private List<ImageButton> mImageButtons;
    public PbxImageButtonRadioLayout(Context context) {
        super(context);
        init(context);
    }

    public PbxImageButtonRadioLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PbxImageButtonRadioLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    private void init(Context context){
        mImageButtons = new ArrayList<>();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        View view = null;
        for (int i = 0, count = getChildCount(); i < count; i++){

            view = getChildAt(i);
            if (view instanceof ImageButton){
                view.setOnClickListener(this);
                mImageButtons.add((ImageButton) view);
            }
        }
    }

  /*  public void setSelectImageButton(ImageButton iv){
        for (ImageButton button : mImageButtons) {
            button.setSelected( button == iv);
        }
    }
    public void setSelectImageButton(@IdRes int id){
        for (ImageButton button : mImageButtons) {
            button.setSelected(button.getId() == id);
        }
    }*/
    public void setSelectImageIndex(int index){
       for (int i = 0, size = mImageButtons.size(); i < size; i++){
           mImageButtons.get(i).setSelected(index == i);
       }
    }

    @Override
    public void onClick(View v) {
        if (v instanceof ImageButton){
            for (ImageButton button : mImageButtons) {
                boolean isSelected = button == v;
                if (isSelected != button.isSelected()){
                    button.setSelected(isSelected);
                    if (isSelected){
                        if (mOnImageButtonRadioListener != null){
                            mOnImageButtonRadioListener.onChecked(button);
                        }
                    }
                }
            }
        }
    }

    private OnImageButtonRadioListener mOnImageButtonRadioListener;

    public void setOnImageButtonRadioListener(OnImageButtonRadioListener onImageButtonRadioListener) {
        mOnImageButtonRadioListener = onImageButtonRadioListener;
    }

    public interface OnImageButtonRadioListener{
        void onChecked(ImageButton view);
    }
}
